package org.zhao.nettydemos.echoServer;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Auther: xiaohui.zhao
 * @Date: 2021/9/15 16:19
 * @Description:
 */
@Slf4j

public class NettyEchoClient {

    private int serverPort;

    private String serverIp;

    Bootstrap bootstrap = new Bootstrap();

    public NettyEchoClient(String serverIp,int serverPort){
        this.serverPort = serverPort;
        this.serverIp = serverIp;
    }

    public static void main(String[] args) {
        new NettyEchoClient("127.0.0.1",18899).runClient();
    }

    public void runClient(){

        EventLoopGroup workerLoopGroup = new NioEventLoopGroup();

        try{
            // 1. 设置反应器轮询组
            bootstrap.group(workerLoopGroup);
            // 2. 设置nio类型的通道
            bootstrap.channel(NioSocketChannel.class);
            // 3. 设置ip + port
            bootstrap.remoteAddress(serverIp,serverPort);
            // 4. 设置通道参数
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            // 5.  装配子通道流水线
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    // 管理子通道中的handler
                    // 向子通道流水线添加一个handler
                    socketChannel.pipeline().addLast(NettyEchoClientHandler.INSTANCE);
                }
            });

            ChannelFuture channelFuture = bootstrap.connect();
            channelFuture.addListener((ChannelFuture fetureListener) -> {
               if(fetureListener.isSuccess()){
                   log.info("EchoClient 客户端连接成功");
               } else{
                   log.info("EchoClient 客户端连接失败");
               }
            });
            channelFuture.sync();  // 阻塞到连接成功

            Channel channel = channelFuture.channel();
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入发送的内容");
            while(scanner.hasNext()){
                String next = scanner.next();
                if("exit".equalsIgnoreCase(next)){
                    break;
                }

                byte[] bytes = (System.currentTimeMillis() + ">>" + next).getBytes(StandardCharsets.UTF_8);

                // 发送bytebuf
                ByteBuf byteBuf = channel.alloc().buffer();
                byteBuf.writeBytes(bytes);

                channel.writeAndFlush(byteBuf);
                System.out.println("请输入发送内容(输入exit 退出)");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            workerLoopGroup.shutdownGracefully();
        }

    }

}